package com.example.mall_system.controller;

import com.example.mall_system.common.Result;
import com.example.mall_system.entity.User;
import com.example.mall_system.entity.LoginResponse;
import com.example.mall_system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        return userService.register(user);
    }
    
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");
        return userService.login(username, password);
    }
    
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestParam Long userId) {
        User user = userService.findById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        // 隐藏密码
        user.setPassword(null);
        return Result.success(user);
    }
    
    // 测试接口：生成密码哈希
    @GetMapping("/test/password")
    public Result<String> generatePasswordHash(@RequestParam String password) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(10);
        String hashedPassword = encoder.encode(password);
        return Result.success(hashedPassword);
    }
}